<template>
  <div class="col card p10">
    <label class="title">温控器设置</label>
    <div class="mt row_center">
      <label>地址:</label>
      <el-input size="small" v-model="ctx.reg_addr" style="width: 60px;"/>
      <label class="ml">数据:</label>
      <el-input size="small" v-model="ctx.reg_value" style="width: 60px;"/>
    </div>
    <div class="mt row_center">
      <el-button @click="onClickWrite" type="warning">写入</el-button>
      <el-button @click="onClickRead" type="primary">读取</el-button>
      <el-button @click="onClickReadTemp">读取温度</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">

import { reactive } from 'vue';
import { dialog } from '../../service/ui';
import { rkc_read, rkc_write } from '../../service/main_cmd';


interface Ctx {
  reg_addr: string,
  reg_value: string,
}

const ctx = reactive<Ctx>({
  reg_addr: '0',
  reg_value: '0',
});

async function onClickRead() {

  try {
    const addr = parseInt(ctx.reg_addr);
    const val = await rkc_read(addr);
    dialog.succ(`数据:${val}`, 3000);
  } catch (msg) {
    dialog.err(msg);
  }

}

async function onClickWrite() {
  try {
    const addr = parseInt(ctx.reg_addr);
    const val = parseInt(ctx.reg_value);
    await rkc_write(addr, val);
    dialog.succ('写入成功');
  } catch (msg) {
    dialog.err(msg);
  }
}

async function onClickReadTemp() {
  try {
    const val = await rkc_read(0x0100);
    let t = val / 10;
    if (val & 0x8000) {
      t = -(0x10000 - val) / 10;
    }
    dialog.succ(`温度:${t}`);
  } catch (msg) {
    dialog.err(msg);
  }
}

</script>
